import { baseRoute , asyncRoutes} from "@/router";

const state = {
  routes: []
}

const mutations = {
  // 更新路由配置
  SET_ROUTE(state, route) {
    state.routes = baseRoute.concat(route)
  },
  /**
 * 
 * @param {*} state 
 * 清空并重置状态中的路由信息至初始状态，即将路由配置清空为一个空数组。
 * 通常在需要彻底刷新路由设置，比如登出操作后，重新设置应用程序的路由场景中使用。
 */
  RESET_ROUTE(state) {
    state.routes = [];
  }
}

const actions = {
  getRouteAction({ commit }, roleIdsStr) {
    return new Promise((resolve, reject)=> {
      // debugger
      let accessedRoutes = [];
      accessedRoutes = filterAsyncRoute(asyncRoutes, roleIdsStr);
      console.log('accessedRoutes11111111111',accessedRoutes);
      commit('SET_ROUTE', accessedRoutes);
      // resolve(state.routes);
      resolve(accessedRoutes);
    })
  }
}
export function filterAsyncRoute(routes, roleIdsStr) {
  // debugger
  // 目的：过滤出当前角色所拥有的路由,放到数组里面
  console.log('routes', routes);
  const arr = [];
  routes.forEach(item => {
    const temp = { ...item };
    if(hasChildren(temp, roleIdsStr)){
      if (temp.children) {
        temp.children = filterAsyncRoute(temp.children, roleIdsStr);
      }
      arr.push(temp);
    }
  });
  return arr
}
export function hasChildren(route, roleIdsStr) {
  // debugger
  let roleIdsArr = roleIdsStr.split(',');
  if(route.meta && route.meta.role) {
    return roleIdsArr.includes(String(route.meta.role))
  }else {
    return true;
  }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}